package com.steptime.framework.mybatis;

import cn.hutool.core.io.FileUtil;
import com.steptime.framework.mybatis.bean.ProductInfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

public class MybatisTester {
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

    /**
     * 简单的mybatis映射查询
     *  如果bean中有多单词命名则需要开启驼峰命名映射
     *  <setting name="mapUnderscoreToCamelCase" value="true"/>
     */
    @Test
    public void printPruduct() {
        /**
         * 1、全局设置项环境配置mapper声明-mybatis-config.xml
         * 2、生成全局唯一的SqlSessionFactory
         * 3、创建SqlSession对象执行位于mapper.xml中的sql语句
         * 4、关闭SqlSession对象
         */
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(FileUtil.file("mybatis-config.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory= sqlSessionFactoryBuilder.build(fileReader);
        SqlSession sqlSession= sqlSessionFactory.openSession();
        List<ProductInfo> productInfoList= sqlSession.selectList("findAll");
        productInfoList.forEach(productInfo ->
                System.out.println(productInfo.getName()+":"+productInfo.getPrice()));
        sqlSession.close();
    }

    /**
     * 一级缓存  SqlSession级别
     * 二级缓存  namespace级别
     */
    @Test
    public void TestMybatisCache() {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(FileUtil.file("mybatis-config.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory= sqlSessionFactoryBuilder.build(fileReader);
        SqlSession sqlSession= sqlSessionFactory.openSession();
        List<ProductInfo> productInfoList= sqlSession.selectList("findAll");
        sqlSession.commit();
        List<ProductInfo> productInfoList2= sqlSession.selectList("findAll");
        //一级缓存：productInfoList和productInfoList2其实是一个对象集合，根据日志显示sql也只是执行了一次
        System.out.println(productInfoList.hashCode()+""+productInfoList2.hashCode());
        sqlSession.close();
    }
}
